import style from './index.module.scss'
import HeaderView from '@/component/Header'
import { Form, Button, Input, Toast } from 'antd-mobile'
import { NavLink } from 'react-router-dom'
import { UserLogin } from '@/api/loginRegister'
import { loginType } from '@/type/loginType'
import { useNavigate } from 'react-router-dom'
import { saveToken } from '@/reduxToolkit/reducers/token'
import { saveProductNum } from '@/reduxToolkit/reducers/productNum'
import { useDispatch } from 'react-redux'
import { GetList } from '@/api/shopcart'

const Login = () => {
  const navigate = useNavigate()
  const dispath = useDispatch()

  // 用户登录
  const onFinish = async (value: loginType) => {
    const res = await UserLogin({email: value.email, password: value.password})
    const res2= await GetList('include=goods')
    try {
      if(res.status === 200) {
        dispath(saveToken(res.data.access_token))
        dispath(saveProductNum(res2.data.data.length))
        Toast.show({ icon: 'success', content: '登录成功', duration: 1500, maskClickable: false, afterClose: () => {
          navigate('/home')
        }})
      }
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <div className={style.headerBox}>
      {/* header--nvabar */}
      <HeaderView title='登录中心' backIcon={false}/>
       
      <div className={style.loginFormBox}>
        <Form layout='horizontal' onFinish={onFinish} footer={
          <>
            <NavLink to='/register' className={style.link}>注册账号</NavLink>
            <Button block type='submit' size='large' className={style.btn}>登录</Button>
          </>
        }>
          <Form.Item name='email' label='邮箱' rules={[{ required: true, message: '邮箱不能为空' }]}>
            <Input placeholder='请输入邮箱' />
          </Form.Item>
          <Form.Item name='password' label='密码' rules={[{ required: true, message: '密码不能为空' }]}>
            <Input placeholder='请输入密码' type='password'/>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login